package com.gitee.cui.server.processor;

import com.gitee.cui.common.common.ProtoInstant;
import com.gitee.cui.common.common.bean.User;
import com.gitee.cui.common.common.bean.msg.ProtoMsg;
import com.gitee.cui.server.builder.LoginResponseBuilder;
import com.gitee.cui.server.server.ServerSession;
import com.gitee.cui.server.server.SessionMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 登录流程处理器
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/28 8:47
 **/
@Service
public class LoginProcessor extends AbstractServerProcessor {

    @Autowired
    private LoginResponseBuilder loginResponseBuilder;

    @Override
    public ProtoMsg.HeadType type() {
        return ProtoMsg.HeadType.LOGIN_REQUEST;
    }

    @Override
    public boolean action(ServerSession session, ProtoMsg.Message message) {
        // 取出请求信息
        ProtoMsg.LoginRequest request = message.getLoginRequest();
        // 消息序列号
        long sequence = message.getSequence();

        // 从请求消息中得到用户信息
        User user = User.fromMsg(request);

        // 校验用户信息
        boolean isValidUser = checkUser(user);
        if (!isValidUser) {
            // 用户无效，构建登陆失败报文
            ProtoInstant.ResultCodeEnum noToken = ProtoInstant.ResultCodeEnum.NO_TOKEN;
            ProtoMsg.Message response = loginResponseBuilder.loginResponse(noToken, sequence, "-1");
            // 发送登录失败报文
            session.writeAndFlush(response);
            return false;
        }

        session.setUser(user);
        session.bind();

        // 构建登陆成功报文
        ProtoInstant.ResultCodeEnum success = ProtoInstant.ResultCodeEnum.SUCCESS;
        ProtoMsg.Message response = loginResponseBuilder.loginResponse(success, sequence, session.getSessionId());
        session.writeAndFlush(response);
        return true;
    }

    /**
     * 校验用户信息
     * @param user 用户信息
     * @return 校验是否成功
     */
    private boolean checkUser(User user) {
        if (SessionMap.inst().hasLogin(user)) {
            return false;
        }
        return true;
    }
}
